//
//  XTDairyViewController.m
//  BeautifulHome
//
//  Created by dlios on 15-5-13.
//  Copyright (c) 2015年 ACE. All rights reserved.
//

#import "XTDairyViewController.h"
#import "XTDairyDetailsViewController.h"
#import "XTDairyTableViewCell.h"
#import "XTNetworkHandle.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "XTMyLoginViewController.h"
#import "XTWriteDairyViewController.h"
#import "AppDelegate.h"
#import "XTMyDairy.h"
#import "XTmyDairyDetailsViewController.h"
@interface XTDairyViewController ()<UITableViewDataSource,UITableViewDelegate, ChuanZhiDelegate>
@property(nonatomic, retain)UITableView *myTable;
@property(nonatomic, retain)UITableView *wangYouTable;
@property(nonatomic, retain)UISegmentedControl *myseg;
@property(nonatomic, retain)UIView *MyDairyView;
@property(nonatomic, retain)UIView *wangYouView;
@property(nonatomic, retain)NSMutableArray *dairyArr;
@property(nonatomic, retain)NSMutableArray *myDairyArr;
@property(nonatomic, retain)XTMyDairy *xtMyDairy;
@property(nonatomic, retain)NSMutableArray *arr;
@end

@implementation XTDairyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    //我的
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"我的" style:UIBarButtonItemStylePlain target:self action:@selector(my)];
    //写日记按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"200"] style:UIBarButtonItemStylePlain target:self action:@selector(writeDairy)];
    
    
    //创建分页控制器
    self.myseg = [[UISegmentedControl alloc]initWithItems:@[@"我的日记",@"网友日记"]];
    _myseg.selectedSegmentIndex = 1;
    _myseg.frame = CGRectMake(120, 30, 100, 30);
    self.navigationItem.titleView = self.myseg;
    [_myseg release];
    [_myseg addTarget:self action:@selector(segAction: ) forControlEvents:UIControlEventValueChanged];
    //我的日记页面
    [self creat];
    [self get];
        
    
    
    
    //网友日记页面
   
    self.nextCursor = 1;
    self.dairyArr = [NSMutableArray array];
    [self creat1];
    self.isUpLoading = NO;
    // 上拉下拉功能
    [self addHeader];
    [self addFooter];
    //[self creatNotificationCenter];
    
}
- (void)get
{
    self.myDairyArr = [NSMutableArray array];
    //归档解档收藏
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //创建文件管理器(单例)
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //添加文件夹
    //拼接文件夹地址
    NSString *filePath = [path stringByAppendingPathComponent:@"收藏"];
    //创建文件夹
    [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *strPath = [filePath stringByAppendingPathComponent:@"myDairy.ddp"];
    self.myDairyArr = [NSKeyedUnarchiver unarchiveObjectWithFile:strPath];
}
- (void)writeDairy
{
    XTWriteDairyViewController *wVC = [[[XTWriteDairyViewController alloc]init]autorelease];
    wVC.delegate = self;
    [self.navigationController pushViewController:wVC animated:YES];
}
- (void)my
{
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (tempAppDelegate.LeftSlideVC.closed)
    {
        [tempAppDelegate.LeftSlideVC openLeftView];
    }
    else
    {
        [tempAppDelegate.LeftSlideVC closeLeftView];
    }
}
- (void)segAction:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        _myTable.hidden = NO;
        _wangYouTable.hidden = YES;
        //把我的日记页面放到前面
        
        [self get];
        [self.myTable reloadData];
    }
    if (seg.selectedSegmentIndex == 1) {
        _myTable.hidden = YES;
        _wangYouTable.hidden = NO;
        //把网友日记页面放到前面
        
    }
}
- (void)getData:(NSInteger)nextCursor
{
#warning 封装AFN的调用
    // 参数1: 网络接口
    // 参数2: 返回数据的Block 参数result中是网络请求的返回数据
    NSString *str = [NSString stringWithFormat:@"http://www.to8to.com/mobileapp/zxdiary.php?action=getdiary&type=2&p=%ld&pg=15&uid=0&digest=0",nextCursor];
    [XTNetworkHandle getDataWithURL:str completion:^(id result) {
        // result为请求接口的返回数据
        //NSLog(@"~~~~~%@", result);
        
        self.nextCursor = self.nextCursor + 1;
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.dairyArr removeAllObjects];
        }

        NSMutableArray *arr = [result objectForKey:@"content"];
        for (NSDictionary *tempDic in arr) {
            XTDairy *xtDairy = [[XTDairy alloc]init];
            [xtDairy setValuesForKeysWithDictionary:tempDic];
            xtDairy.mytypename = [tempDic objectForKey:@"typename"];
            [_dairyArr addObject:xtDairy];
            [xtDairy release];
            //NSLog(@"$$$%@",_dairyArr);
        }
        //结束底部刷新效果
        [self.wangYouTable footerEndRefreshing];
        //结束头部刷新效果
        [self.wangYouTable headerEndRefreshing];
        //重新加载数据
        [self.wangYouTable reloadData];
    }];
 
}
//下拉刷新
- (void)addHeader
{
    __block XTDairyViewController *cVC = self;
    // 添加下拉刷新头部控件
    [self.wangYouTable addHeaderWithCallback:^{
        cVC.isUpLoading = NO;
        //重新请求数据
        [cVC getData:0];
    }];
    //自动刷新
    [self.wangYouTable headerBeginRefreshing];
}
- (void)addFooter
{
    __block XTDairyViewController *xVC = self;
    // 添加上拉刷新尾部控件
    [self.wangYouTable addFooterWithCallback:^{
        xVC.isUpLoading = YES;
        //请求更多数据
        [xVC getData:xVC.nextCursor];
    }];
}






//创建tableView
- (void)creat
{
    //我的日记
    self.myTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    
    [self.view addSubview:_myTable];
}
- (void)creat1
{
    //网友日记
    self.wangYouTable = [[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain]autorelease];
    _wangYouTable.delegate = self;
    _wangYouTable.dataSource = self;
    _wangYouTable.rowHeight = 120;
    [self.view addSubview:_wangYouTable];
    
    
    
}

#warning 4.判断编辑状态进行删除或者添加  commitEditingStyle
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.myTable) {
        
        self.myDairyArr = [NSMutableArray array];
        //归档解档收藏
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        //创建文件管理器(单例)
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //添加文件夹
        //拼接文件夹地址
        NSString *filePath = [path stringByAppendingPathComponent:@"收藏"];
        //创建文件夹
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        NSString *strPath = [filePath stringByAppendingPathComponent:@"myDairy.ddp"];
        self.myDairyArr = [NSKeyedUnarchiver unarchiveObjectWithFile:strPath];
        //通过editingStyle判断状态,执行删除/添加操作
        //删除操作
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            NSMutableArray *marr = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:strPath]];
            [marr removeObjectAtIndex:indexPath.row];
            
            
            //1.删除cell之前 先从数组中对应位置 删除数据
            [_myDairyArr removeObjectAtIndex:indexPath.row];
            //2.删除的信息需要被存放在一个数组中
            NSArray *arr = @[indexPath];
            //3.让视图和数据匹配
            //参数1: 删除信息的数组
            //参数2: 删除操作的动画效果
            [_myTable deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationLeft];
            [NSKeyedArchiver archiveRootObject:marr toFile:strPath];
        }
    }
    
}
//删除样式 title(确认删除)
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _myTable) {
        if (self.myDairyArr == nil) {
            return 1;
        } else {
            return _myDairyArr.count;
        }
    }else {
        return _dairyArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _myTable){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"]autorelease];
        }
        if (self.myDairyArr == nil) {
            cell.textLabel.text = @"还没有自己的日记呦~~~";
            cell.detailTextLabel.text = @"快点击右上角按钮添加属于自己的装修日记吧";
        } else {
            XTMyDairy *xtMyDairy = [[XTMyDairy alloc] init];
            xtMyDairy = self.myDairyArr[indexPath.row];
            cell.textLabel.text = xtMyDairy.myDairyTitle;
            cell.detailTextLabel.text = xtMyDairy.myDairyContent;
            //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        }
        return cell;
    }else{
        XTDairyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (cell == nil) {
            cell = [[[XTDairyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"]autorelease];
        }
        //网游日记
        XTDairy *xtdairy = _dairyArr[indexPath.row];
        cell.nameLabel.text = xtdairy.author;
        //cell.styleLabel.text = xtdairy.mytypename;
        cell.timeLabel.text = xtdairy.dateline;
        NSString *str1 = [NSString stringWithFormat:@"     %@",xtdairy.subject];
        cell.titleLabel.text = str1;
        NSString *str = [NSString stringWithFormat:@"浏览: %@",xtdairy.views];
        cell.answerLabel.text = str;
        
        [cell.myimageView sd_setImageWithURL:[NSURL URLWithString:xtdairy.avatar] placeholderImage:[UIImage imageNamed:@"my.jpg"]];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _myTable){
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        XTmyDairyDetailsViewController *xmDVC = [[[XTmyDairyDetailsViewController alloc]init]autorelease];
        
        XTMyDairy *xtMyDairy = _myDairyArr[indexPath.row];
        xmDVC.titleName = xtMyDairy.myDairyTitle;
        xmDVC.commentName = xtMyDairy.myDairyContent;
        
        [self.navigationController pushViewController:xmDVC animated:YES];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XTDairyDetailsViewController *xDVC = [[[XTDairyDetailsViewController alloc]init]autorelease];
        XTDairy *xtDairy = _dairyArr[indexPath.row];
        
        xDVC.datelineXq = xtDairy.dateline;
        xDVC.authorXq = xtDairy.author;
        xDVC.subjectXq = xtDairy.subject;
        xDVC.tidXq = xtDairy.tid;
        //xDVC.authoridXq = xtDairy.authorid;
        xDVC.avatarXq = xtDairy.avatar;
    
    [self.navigationController pushViewController:xDVC animated:YES];
    }
}
- (void)getPrama:(XTMyDairy *)prama
{
    [self.myDairyArr addObject:prama];
    [self.myTable reloadData];
}
- (void)creatNotificationCenter
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changeColor:) name:@"color" object:nil];
}

- (void)changeColor:(NSNotification *)noti
{
    self.navigationController.navigationBar.translucent = NO;
    self.backgroundColor = noti.object;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:self.backgroundColor] forBarMetrics:UIBarMetricsDefault];
}
//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    //    NSLog(@"viewWillDisappear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
//}
//
//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    //    NSLog(@"viewWillAppear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:YES];
//}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
